import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:grab_the_order/app/data/models/log_model.dart';
import 'package:intl/intl.dart';

class LogService extends GetxService {
  final _box = GetStorage();
  final String _logKey = 'app_logs';
  final DateFormat _formatter = DateFormat('HH:mm:ss');

  final RxList<LogModel> logs = <LogModel>[].obs;

  @override
  void onInit() {
    super.onInit();
    _loadLogs();
  }
  
  void _loadLogs() {
    List<dynamic>? storedLogs = _box.read<List<dynamic>>(_logKey);
    if (storedLogs != null) {
      logs.value = storedLogs
          .map((logMap) => LogModel.fromMap(Map<String, dynamic>.from(logMap)))
          .toList();
    }
  }

  Future<void> addLog(String message, {LogLevel level = LogLevel.info}) async {
    final log = LogModel(timestamp: DateTime.now(), message: message, level: level);
    // 插入到列表开头，让最新的日志显示在最上面
    logs.insert(0, log);
    // 保持最多200条日志，防止无限增长
    if (logs.length > 200) {
      logs.removeLast();
    }
    await _box.write(_logKey, logs.map((l) => l.toMap()).toList());
  }

  Future<void> clearLogs() async {
    logs.clear();
    await _box.remove(_logKey);
  }

  String formatLog(LogModel log) {
    return "[${_formatter.format(log.timestamp)}] ${log.message}";
  }
}